package jm.nj.demo22mian.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUitils {
    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;

    static {
        try {
            //加载jdbc配置文件
            initConfig();
            //注册驱动
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

    }

    /*
     * 加载jdbc.properties文件
     * */
    private static void initConfig() {
        Properties prop = new Properties();
        InputStream is = null;

        is = JdbcUitils.class.getResourceAsStream("jdbc.properties");
        try {
            prop.load(is);
            driver = prop.getProperty("driver");
            url = prop.getProperty("url");
            username = prop.getProperty("username");
            password = prop.getProperty("password");
        } catch (IOException e) {
        }finally {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }

    public static void main(String[] args) {
        initConfig();
        System.out.println(1);
    }

    /*
    *获取数据库连接
    *
    * @return
     * @throws SQLException
    * */

    public static Connection getConnection() throws SQLException {
        Connection conn = DriverManager.getConnection(url, username, password);
        return conn;
    }

    /**释放资源
     * @param conn
     * @param stmt
     * @param rs
     */
    public static void closeResource(Connection conn, Statement stmt, ResultSet rs){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (stmt != null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


}
